package cn.stard.controller;

import cn.stard.domian.User;
import cn.stard.handler.UserFallBackHandle;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RefreshScope//实时刷新远程配置
@RestController
public class UserController {

      /*
        1.sentinel有五种规则我们可以配置
        2.当触发了配置的规则 那么sentinel会抛出blockException
        3.当配置了blockHandler的时候 那么就会捕获blockException 并进入指定的方法
        4.当配置了fallback,那么程序出现异常 就会进入指定的方法
        5.如果fallback和blockHandler同时触发 那么会进到blockHandler指定的方法
     */

    @GetMapping("/getUserByid/{id}")
    @SentinelResource(value = "getUserById",
            blockHandlerClass = UserFallBackHandle.class,
            blockHandler ="getUserByIdBlockHandler" ,
            fallback = "getUserByIdBlockfallback"       )
    public User getUserById(@PathVariable Long id) {
        int i = 1/0;
        return new User().setUsername("进入方法").setId(1l);
    }

    public User getUserByIdBlockfallback(@PathVariable Long id, Throwable e) {
        return new User().setUsername("进入代码托底数据").setId(2l);
    }

    public User getUserByIdBlockHandler(@PathVariable Long id, BlockException e) {
        return new User().setUsername("进入限流方法托底数据1111").setId(2l);
    }
}
